﻿using AutoMapper;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Events;
using Prism.Ioc;
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows;
using TransformerManager.Shared.Dto.Transformer;
using TransformerManager.Shared.Helper.HttpParams;
using TransformerManager.WPF.Common.Helper;
using TransformerManager.WPF.Common.Helper.Events;
using TransformerManager.WPF.Common.Http;
using TransformerManager.WPF.Common.Http.Service;
using TransformerManager.WPF.Common.Views;
using hc = HandyControl.Controls;

namespace TransformerManager.WPF.Common.ViewModels
{
    public class DetailInfoTemplateViewModel : BindableBase, INavigationAware
    {
        private readonly IRegionManager _regionManager;
        private readonly IContainerExtension _container;
        private readonly IEventAggregator _eventAggregator;
        private readonly ITransformerService _transformerService;
        private readonly IMapper _mapper;

        private NavigationContext _navigationContext;
        public DetailInfoTemplateViewModel(
            IMapper mapper,
            IRegionManager regionManager,
            IEventAggregator eventAggregator,
            ITransformerService transformerService,
            IContainerExtension container)
        {
            _regionManager = regionManager;
            _transformerService = transformerService;
            _container = container;
            _eventAggregator = eventAggregator;
            _mapper = mapper;

            InitAllCmd();
        }

        #region Command

        public DelegateCommand UpdateDoneCmd { private set; get; }

        public DelegateCommand EditCmd { private set; get; }

        public DelegateCommand CancelEditCmd { private set; get; }

        public DelegateCommand DeleteCmd { private set; get; }


        #endregion


        #region 方法的定义

        private TransformerDto _transformerDto;
        public TransformerDto TransformerDto
        {
            set
            {
                _transformerDto = value;

                RaisePropertyChanged();
            }
            get
            {
                return _transformerDto;
            }
        }

        private Visibility _isLoadingVisible = Visibility.Collapsed;
        public Visibility IsLoadingVisible
        {
            set
            {
                _isLoadingVisible = value;

                RaisePropertyChanged();
            }
            get
            {
                return _isLoadingVisible;
            }
        }

        private bool _isBtnDeleteEditable = true;
        public bool IsBtnDeleteEditable
        {
            get { return _isBtnDeleteEditable;  }
            set { _isBtnDeleteEditable = value; RaisePropertyChanged(); }
        }

        private bool _isBtnEditEditable = true;
        public bool IsBtnEditEditable
        {
            get { return _isBtnEditEditable; }
            set { _isBtnEditEditable = value; RaisePropertyChanged(); }
        }

        private bool _isBtnCancelEditable = false;
        public bool IsBtnCancelEditable
        {
            get { return _isBtnCancelEditable; }
            set { _isBtnCancelEditable = value; RaisePropertyChanged(); }
        }

        private bool _isBtnDoneEditable = false;
        public bool IsBtnDoneEditable
        {
            get { return _isBtnDoneEditable; }
            set { _isBtnDoneEditable = value; RaisePropertyChanged(); }
        }


        #endregion


        #region 函数的定义

        private void InitAllCmd()
        {
            UpdateDoneCmd = new DelegateCommand(async () =>
            {
                await UpdateTransformerInfo();
            });

            CancelEditCmd = new DelegateCommand(CancelEdit);

            EditCmd = new DelegateCommand(EditTransformerInfo);

            DeleteCmd = new DelegateCommand(async () =>
            {
                await DeleteTransformerInfo();
            });
        }

        /// <summary>
        /// 部分页面跳转至ProjectInfoTemplate页面
        /// </summary>
        private void NavigateToProjectInfoTemplatePage()
        {
            _regionManager.RequestNavigate("DetailInfoTemplateRegion", nameof(ProjectInfoTemplate));

            CustomiseRegionManager.PreLoadRegions(_regionManager);
        }

        /// <summary>
        /// 更新上传数据
        /// </summary>
        public async Task UpdateTransformerInfo()
        {
            var dialogResult = HandyControl.Controls.MessageBox.Show(
                "是否完成编辑?",
                "确认",
                MessageBoxButton.YesNo,
                MessageBoxImage.Question);

            if (dialogResult == MessageBoxResult.No) return;

            _transformerDto.UpdateTime = DateTime.UtcNow;
            // 请求数据
            var result = await _transformerService
                .UpdateTransformerInfoByIdAsync(_transformerDto.Id, _transformerDto);
            if (!result.Success)
            {
                hc.Growl.Error(
                        $"响应信息: {result.Message}",
                        "Notification");
                return;
            }
            hc.Growl.Success($"响应信息：{result.Message}", "Notification");

            // UI变换
            IsBtnDeleteEditable = true;
            IsBtnEditEditable = true;
            IsBtnCancelEditable = false;
            IsBtnDoneEditable = false;
            _eventAggregator.GetEvent<DetailInfoPageEvent>().Publish(false);
        }

        /// <summary>
        /// 取消编辑
        /// </summary>
        private void CancelEdit()
        {
            var result = HandyControl.Controls.MessageBox.Show(
                "是否取消编辑?",
                "放弃编辑?",
                MessageBoxButton.YesNo,
                MessageBoxImage.Question);

            if (result == MessageBoxResult.No) return;

            // UI变换
            IsBtnDeleteEditable = true;
            IsBtnEditEditable = true;
            IsBtnCancelEditable = false;
            IsBtnDoneEditable = false;
            _eventAggregator.GetEvent<DetailInfoPageEvent>().Publish(false);
        }

        /// <summary>
        /// 编辑
        /// </summary>
        private void EditTransformerInfo()
        {
            // UI变换
            IsBtnDeleteEditable = false;
            IsBtnEditEditable = false;
            IsBtnCancelEditable = true;
            IsBtnDoneEditable = true;
            _eventAggregator.GetEvent<DetailInfoPageEvent>().Publish(true);
        }

        /// <summary>
        /// 删除当前所有数据
        /// </summary>
        private async Task DeleteTransformerInfo()
        {
            var dialogResult = HandyControl.Controls.MessageBox.Show(
                "是否删除当前项目的所有数据?",
                "删除?",
                MessageBoxButton.YesNo,
                MessageBoxImage.Question);

            if (dialogResult == MessageBoxResult.No) return;

            // 请求删除
            var result = await _transformerService.DeleteTransformerByIdAsync(_transformerDto.Id);
            if (!result.Success)
            {
                hc.Growl.Error(
                        $"响应信息: {result.Message}",
                        "Notification");
                return;
            }

            hc.Growl.Success($"响应信息：{result.Message}", "Notification");

            // UI变换
            IsBtnDeleteEditable = true;
            IsBtnEditEditable = true;
            IsBtnCancelEditable = false;
            IsBtnDoneEditable = false;

            // 删除后跳转回上一个页面
            _navigationContext.NavigationService.Journal.GoBack();
        }

        #endregion


        #region 接口实现的函数

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            _navigationContext = navigationContext;
            // 由ProjectListTemplate页面双击项目传递进来的Transformer数据
            TransformerDto = navigationContext.Parameters.GetValue<TransformerDto>("TransformerDto");

            IsLoadingVisible = Visibility.Visible;

            NavigateToProjectInfoTemplatePage();

            IsLoadingVisible = Visibility.Collapsed;
        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
            // UI变换
            IsBtnDeleteEditable = true;
            IsBtnEditEditable = true;
            IsBtnCancelEditable = false;
            IsBtnDoneEditable = false;
            _eventAggregator.GetEvent<DetailInfoPageEvent>().Publish(false);

            CustomiseRegionManager.RemoveRegions(navigationContext);
        }

        #endregion

    }
}
